import {useSSE} from "@/hook/useSSE.ts";
import {computed, onActivated, onDeactivated, onMounted, ref} from "vue";
import sysMonitorApi from "../api/SysMonitorApi";
import type OperateSystemRealtimeResp from "@/view/sys/monitor/type/resp/OperateSystemRealtimeResp.ts";
import type JvmRealtimeResp from "@/view/sys/monitor/type/resp/JvmRealtimeResp.ts";
import type OperateSystemBasicResp from "@/view/sys/monitor/type/resp/OperateSystemBasicResp.ts";
import type JvmBasicResp from "@/view/sys/monitor/type/resp/JvmBasicResp.ts";
import type ThreadInfoResp from "@/view/sys/monitor/type/resp/ThreadInfoResp.ts";
import type DatabaseInfoRealtimeResp from "@/view/sys/monitor/type/resp/DatabaseInfoRealtimeResp.ts";
import type DiskInfoResp from "@/view/sys/monitor/type/resp/DiskInfoResp.ts";
import type JvmArgumentsResp from "@/view/sys/monitor/type/resp/JvmArgumentsResp.ts";

/**
 * created by yangtong on 2025/7/13 下午9:11
 */
export function useData() {

    const {isConnected, connect, on, disconnect} = useSSE()

    // 订阅了SSE事件的数组
    const unsubArr: (() => void)[] = []

    // 操作系统基础信息
    const operateSystemBasic = ref<OperateSystemBasicResp>()

    // 操作系统实时最新数据
    const operateSystemRealtime = ref<OperateSystemRealtimeResp>()

    // 操作系统实时数据历史记录
    const operateSystemRealtimeHistory = ref<OperateSystemRealtimeResp[]>([])

    // 操作系统磁盘信息
    const diskInfo = ref<DiskInfoResp>()

    // JVM启动参数
    const jvmArg = ref<JvmArgumentsResp>()

    // JVM基本信息
    const jvmBasic = ref<JvmBasicResp>()

    // JVM实时最新数据
    const jvmRealtime = ref<JvmRealtimeResp>()

    // JVM实时数据历史记录
    const jvmRealtimeHistory = ref<JvmRealtimeResp[]>([])

    // 实时数据历史记录最大保留条数
    const maxHistoryLength = 30

    // 线程信息
    const threads = ref<ThreadInfoResp>()

    // 数据库连接池信息
    const databaseInfo = ref<DatabaseInfoRealtimeResp>()

    /**
     * 根据比例，返回不同的颜色表示危险等级
     * @param rate 0~1
     */
    const getUsageColor = (rate: number) => {
        if (rate > 0.95) return '#8B0000'  // 黑红色
        if (rate >= 0.9) return '#F56C6C' // 红色
        if (rate >= 0.66) return '#E6A23C' // 橙色
        return '#67C23A'                 // 绿色
    }

    /**
     * 通过SSE事件接受操作系统实时数据
     */
    const acceptOperateSystemRealtime = async () => {
        // 监听系统实时指标
        return on('SysMonitor-OperateSystemRealtime', (event: MessageEvent) => {
            try {
                const operateSystemRealtimeResp: OperateSystemRealtimeResp = JSON.parse(event.data)
                operateSystemRealtime.value = operateSystemRealtimeResp

                if (operateSystemRealtimeHistory.value.length >= maxHistoryLength) {
                    operateSystemRealtimeHistory.value.shift()
                }

                // 添加到历史记录
                operateSystemRealtimeHistory.value.push(operateSystemRealtimeResp)
            } catch (error) {
                console.error('解析 SSE 操作系统实时指标数据失败:', error)
            }
        })
    }

    /**
     * 通过SSE事件接受JVM实时数据
     */
    const acceptJvmRealtime = async () => {
        // 监听系统实时指标
        return on('SysMonitor-JvmRealtime', (event: MessageEvent) => {
            try {
                const jvmRealtimeResp: JvmRealtimeResp = JSON.parse(event.data)
                jvmRealtime.value = jvmRealtimeResp

                if (jvmRealtimeHistory.value.length >= maxHistoryLength) {
                    jvmRealtimeHistory.value.shift()
                }

                // 添加到历史记录
                jvmRealtimeHistory.value.push(jvmRealtimeResp)
            } catch (error) {
                console.error('解析 SSE 收到JVM实时指标:', error)
            }
        })
    }

    /**
     * 通过SSE事件接受JVM实时线程数据
     */
    const acceptThreadRealtime = async () => {
        // 监听系统实时指标
        return on('SysMonitor-TheadRealtime', (event: MessageEvent) => {
            try {
                threads.value = JSON.parse(event.data)
            } catch (error) {
                console.error('解析 SSE 收到线程实时指标:', error)
            }
        })
    }

    /**
     * 通过SSE事件接受JVM实时数据库连接池数据
     */
    const acceptDatabaseRealtime = async () => {
        // 监听系统实时指标
        return on('SysMonitor-DatabaseInfoRealtime', (event: MessageEvent) => {
            try {
                databaseInfo.value = JSON.parse(event.data)
            } catch (error) {
                console.error('解析 SSE 收到数据库连接池实时指标:', error)
            }
        })
    }

    /**
     * 获取操作系统基础信息
     */
    const fetchOperateSystemBasic = async () => {
        try {
            operateSystemBasic.value = await sysMonitorApi.operateSystemBasic()
        } catch (error) {
            console.error('获取操作系统基础信息失败:', error)
        }
    }

    /**
     * 获取操作系统磁盘信息
     */
    const fetchDiskBasic = async () => {
        try {
            diskInfo.value = await sysMonitorApi.disk()
        } catch (error) {
            console.error('获取操作系统基础信息失败:', error)
        }
    }

    // 添加获取JVM启动参数的函数
    const fetchJvmArg = async () => {
        try {
            jvmArg.value = await sysMonitorApi.arguments()
        } catch (error) {
            console.error('获取JVM启动参数失败:', error)
        }
    }

    /**
     * 获取JVM基本信息
     */
    const fetchJvmBasic = async () => {
        try {
            jvmBasic.value = await sysMonitorApi.jvmBasic()
        } catch (error) {
            console.error('获取JVM基本信息失败:', error)
        }
    }

    /**
     * 操作系统磁盘信息
     */
    const diskUsageChart = computed(() => {
        if (!diskInfo.value?.partitions) return null

        const partitions = diskInfo.value.partitions
        const partitionNames = partitions.map(p => p.name)
        const usageRateData = partitions.map(p => Number(p.usageRate.toFixed(2)))

        return {
            title: {
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: function (params: any) {
                    const partition = partitions[params.dataIndex]
                    return `
                    <div style="text-align: left;">
                        <strong>${partition.name} </strong><br/>
                        挂载点: ${partition.mountPoint}<br/>
                        总容量: ${partition.totalSpaceGB.toFixed(2)} GB<br/>
                        已使用: ${partition.usedSpaceGB.toFixed(2)} GB<br/>
                        可用空间: ${partition.usableSpaceGB.toFixed(2)} GB<br/>
                        使用率: <span style="color: ${getUsageColor(partition.usageRate / 100)}">${partition.usageRate.toFixed(2)}%</span>
                    </div>
                `
                }
            },
            grid: {
                top: 60,
                left: '3%',
                right: '3%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: partitionNames,
                axisLabel: {
                    fontSize: 14,
                    fontWeight: 'bold'
                }
            },
            yAxis: {
                type: 'value',
                name: '使用率 (%)',
                axisLabel: {
                    formatter: '{value}%'
                },
                nameTextStyle: {
                    color: '#666'
                },
                min: 0,
                max: 100
            },
            series: [
                {
                    name: '磁盘使用率',
                    type: 'bar',
                    data: usageRateData.map((value, index) => ({
                        value,
                        itemStyle: {
                            color: getUsageColor(value / 100)
                        }
                    })),
                    barWidth: '60%',
                    label: {
                        show: true,
                        position: 'top',
                        formatter: '{c}%',
                        fontSize: 12,
                        fontWeight: 'bold'
                    }
                }
            ]
        }
    })

    /**
     * 堆内存使用率仪表盘图表配置
     */
    const heapMemoryGaugeChart = computed(() => {
        if (!jvmRealtime.value) return null

        const heapUsageRate = Number((jvmRealtime.value.heapMemoryUsageRate * 100).toFixed(1))

        return {
            title: {
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            },
            grid: {
                left: 0,
                right: 0,
                top: 0,
                bottom: 0,
                containLabel: false
            },
            tooltip: {
                formatter: function (params: any) {
                    return `${params.seriesName}<br/>${params.name}: ${params.value}%`
                }
            },
            series: [
                {
                    name: '堆内存使用率',
                    type: 'gauge',
                    center: ['50%', '50%'],
                    radius: '95%',
                    min: 0,
                    max: 100,
                    splitNumber: 10,
                    axisLine: {
                        lineStyle: {
                            width: 8,
                            color: [
                                [0.66, '#67C23A'],
                                [0.9, '#E6A23C'],
                                [0.95, '#F56C6C'],
                                [1, '#8B0000']
                            ]
                        }
                    },
                    axisTick: {
                        distance: -15,
                        length: 8,
                        lineStyle: {
                            color: '#fff',
                            width: 2
                        }
                    },
                    splitLine: {
                        distance: -20,
                        length: 15,
                        lineStyle: {
                            color: '#fff',
                            width: 3
                        }
                    },
                    axisLabel: {
                        color: 'inherit',
                        distance: 25,
                        fontSize: 12,
                        formatter: '{value}%'
                    },
                    pointer: {
                        icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
                        length: '30%',
                        width: 8,
                        offsetCenter: [0, '-40%'],
                        itemStyle: {
                            color: 'inherit'
                        }
                    },
                    detail: {
                        valueAnimation: true,
                        fontSize: 20,
                        fontWeight: 'bold',
                        color: 'inherit',
                        formatter: '{value}%',
                        offsetCenter: [0, '10%']
                    },
                    data: [
                        {
                            value: heapUsageRate,
                        }
                    ]
                }
            ]
        }
    })

    /**
     * 操作系统实时指标趋势图
     */
    const operateSystemRealtimeChart = computed(() => {
        if (operateSystemRealtimeHistory.value.length === 0) return null

        const times = operateSystemRealtimeHistory.value.map(item =>
            new Date(item.timestamp).toLocaleTimeString()
        )

        // CPU使用率 (百分比)
        const cpuUsageRate = operateSystemRealtimeHistory.value.map(item => Number(item.cpuUsageRate.toFixed(2)))
        // 内存使用率 (百分比)
        const physicalMemoryUsageRate = operateSystemRealtimeHistory.value.map(item =>
            Number((item.physicalMemoryUsageRate * 100).toFixed(2))
        )
        // 已使用物理内存 - 转换为GB
        const usedPhysicalMemoryGB = operateSystemRealtimeHistory.value.map(item =>
            Number((item.usedPhysicalMemory / (1024 * 1024 * 1024)).toFixed(2))
        )

        // 计算内存Y轴的合理最大值
        const maxMemoryGB = Math.max(...usedPhysicalMemoryGB)
        const memoryYAxisMax = Math.ceil(maxMemoryGB * 1.2)

        return {
            title: {
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                },
                formatter: function (params: any) {
                    let result = params[0].name + '<br/>'
                    params.forEach((item: any) => {
                        if (item.seriesName === '已使用内存') {
                            // 显示GB单位
                            result += `${item.seriesName}: ${item.value}GB<br/>`
                        } else {
                            // CPU使用率和物理内存使用率显示百分比
                            result += `${item.seriesName}: ${item.value}%<br/>`
                        }
                    })
                    return result
                }
            },
            legend: {
                data: ['CPU使用率', '物理内存使用率', '已使用物理内存'],
                top: 35
            },
            grid: {
                top: 80,
                left: '3%',
                right: '10%', // 为右侧Y轴留出空间
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: times
            },
            yAxis: [
                {
                    type: 'value',
                    name: '百分比 (%)',
                    position: 'left',
                    axisLabel: {
                        formatter: '{value}%'
                    },
                    nameTextStyle: {
                        color: '#666'
                    },
                    min: 0,
                    max: 100
                },
                {
                    type: 'value',
                    name: '内存 (GB)',
                    position: 'right',
                    axisLabel: {
                        formatter: '{value}GB'
                    },
                    nameTextStyle: {
                        color: '#666'
                    },
                    min: 0,
                    max: memoryYAxisMax > 0 ? memoryYAxisMax : 16
                }
            ],
            series: [
                {
                    name: 'CPU使用率',
                    type: 'line',
                    yAxisIndex: 0, // 使用左侧Y轴 (百分比)
                    smooth: true,
                    data: cpuUsageRate,
                    itemStyle: {color: '#ff6b6b'},
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                {offset: 0, color: 'rgba(255, 107, 107, 0.3)'},
                                {offset: 1, color: 'rgba(255, 107, 107, 0.1)'}
                            ]
                        }
                    }
                },
                {
                    name: '物理内存使用率',
                    type: 'line',
                    yAxisIndex: 0, // 使用左侧Y轴 (百分比)
                    smooth: true,
                    data: physicalMemoryUsageRate,
                    itemStyle: {color: '#4caf50'},
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                {offset: 0, color: 'rgba(76, 175, 80, 0.2)'},    // 更透明
                                {offset: 1, color: 'rgba(76, 175, 80, 0.01)'}
                            ]
                        }
                    }
                },
                {
                    name: '已使用物理内存',
                    type: 'line',
                    yAxisIndex: 1, // 使用右侧Y轴 (GB)
                    smooth: true,
                    data: usedPhysicalMemoryGB,
                    itemStyle: {color: '#00bcd4'},
                    lineStyle: {
                        width: 2
                    }
                },
            ]
        }
    })

    /**
     * JVM实时指标趋势图
     */
    const jvmRealtimeChart = computed(() => {
        if (jvmRealtimeHistory.value.length === 0) return null

        const times = jvmRealtimeHistory.value.map(item =>
            new Date(item.timestamp).toLocaleTimeString()
        )

        // 堆内存使用率 (百分比)
        const heapMemoryUsageRate = jvmRealtimeHistory.value.map(item => Number((item.heapMemoryUsageRate * 100).toFixed(2)))
        // 非堆内存使用率 (百分比)
        const nonHeapMemoryUsageRate = jvmRealtimeHistory.value.map(item => Number((item.nonHeapMemoryUsageRate * 100).toFixed(2)))

        // 已使用堆内存 (转换为MB)
        const usedHeapMemoryMB = jvmRealtimeHistory.value.map(item => Number((item.usedHeapMemory / (1024 * 1024)).toFixed(2)))
        // 已使用非堆内存 (转换为MB)
        const usedNonHeapMemoryMB = jvmRealtimeHistory.value.map(item => Number((item.usedNonHeapMemory / (1024 * 1024)).toFixed(2)))

        // 计算内存Y轴的合理最大值
        const maxMemoryMB = Math.max(...usedHeapMemoryMB, ...usedNonHeapMemoryMB)
        const memoryYAxisMax = Math.ceil(maxMemoryMB * 1.2)

        return {
            title: {
                left: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 'bold'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                },
                formatter: function (params: any) {
                    let result = params[0].name + '<br/>'
                    params.forEach((item: any) => {
                        if (item.seriesName.includes('使用率')) {
                            result += `${item.seriesName}: ${item.value}%<br/>`
                        } else {
                            result += `${item.seriesName}: ${item.value}MB<br/>`
                        }
                    })
                    return result
                }
            },
            legend: {
                data: ['已使用堆内存', '堆内存使用率', '已使用非堆内存', '非堆内存使用率'],
                top: 35
            },
            grid: {
                top: 80,
                left: '3%',
                right: '10%', // 为右侧Y轴留出空间
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: times
            },
            yAxis: [
                {
                    type: 'value',
                    name: '使用率 (%)',
                    position: 'left',
                    axisLabel: {
                        formatter: '{value}%'
                    },
                    nameTextStyle: {
                        color: '#666'
                    },
                    min: 0,
                    max: 100
                },
                {
                    type: 'value',
                    name: '内存 (MB)',
                    position: 'right',
                    axisLabel: {
                        formatter: '{value}MB'
                    },
                    nameTextStyle: {
                        color: '#666'
                    },
                    min: 0,
                    max: memoryYAxisMax > 0 ? memoryYAxisMax : 1024
                }
            ],
            series: [
                {
                    name: '已使用堆内存',
                    type: 'line',
                    yAxisIndex: 1, // 使用右侧Y轴 (MB)
                    smooth: true,
                    data: usedHeapMemoryMB,
                    itemStyle: {color: '#52c41a'}, // 深蓝色，与堆内存使用率(浅蓝)成组
                    lineStyle: {
                        width: 2
                    }
                },
                {
                    name: '堆内存使用率',
                    type: 'line',
                    yAxisIndex: 0, // 使用左侧Y轴 (百分比)
                    smooth: true,
                    data: heapMemoryUsageRate,
                    itemStyle: {color: '#1890ff'},
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                {offset: 0, color: 'rgba(24, 144, 255, 0.4)'},
                                {offset: 1, color: 'rgba(24, 144, 255, 0.1)'}
                            ]
                        }
                    }
                },
                {
                    name: '已使用非堆内存',
                    type: 'line',
                    yAxisIndex: 1, // 使用右侧Y轴 (MB)
                    smooth: true,
                    data: usedNonHeapMemoryMB,
                    itemStyle: {color: '#fa8c16'}, // 深绿色，与非堆内存使用率(浅绿)成组
                    lineStyle: {
                        width: 2
                    }
                },
                {
                    name: '非堆内存使用率',
                    type: 'line',
                    yAxisIndex: 0, // 使用左侧Y轴 (百分比)
                    smooth: true,
                    data: nonHeapMemoryUsageRate,
                    itemStyle: {color: '#ff7875'},
                    areaStyle: {
                        color: {
                            type: 'linear',
                            x: 0, y: 0, x2: 0, y2: 1,
                            colorStops: [
                                {offset: 0, color: 'rgba(255, 120, 117, 0.4)'},
                                {offset: 1, color: 'rgba(255, 120, 117, 0.1)'}
                            ]
                        }
                    }
                },
            ]
        }
    })

    // 页面挂载时，获取一些静态数据
    onMounted(async () => {
        // 初始加载其他非SSE实时推送的数据
        await Promise.all([
            fetchOperateSystemBasic(),
            fetchJvmArg(),
            fetchDiskBasic(),
            fetchJvmBasic()
        ])
    })

    // 页面激活时，连接SSE获取动态数据
    onActivated(async () => {
        // 连接到SSE接口
        connect()

        // 获取操作系统实时数据
        const operateSystemRealtimeUnsub = await acceptOperateSystemRealtime()
        // 获取JVM系统实时数据
        const jvmRealtimeUnsub = await acceptJvmRealtime()
        // 获取JVM线程信息
        const threadRealtimeUnsub = await acceptThreadRealtime()
        // 获取数据库连接池信息
        const databaseInfoRealtimeUnsub = await acceptDatabaseRealtime()

        // SSE事件反注册
        if (operateSystemRealtimeUnsub) unsubArr.push(operateSystemRealtimeUnsub)
        if (jvmRealtimeUnsub) unsubArr.push(jvmRealtimeUnsub)
        if (threadRealtimeUnsub) unsubArr.push(threadRealtimeUnsub)
        if (databaseInfoRealtimeUnsub) unsubArr.push(databaseInfoRealtimeUnsub)
    })

    onDeactivated(() => {
        unsubArr.forEach(unsub => unsub())
        unsubArr.length = 0
        // 断开连接
        disconnect()
    })

    return {
        operateSystemBasic,
        operateSystemRealtime,
        operateSystemRealtimeHistory,
        diskInfo,
        jvmArg,
        jvmBasic,
        jvmRealtime,
        jvmRealtimeHistory,
        maxHistoryLength,
        threads,
        databaseInfo,
        getUsageColor,
        acceptOperateSystemRealtime,
        acceptJvmRealtime,
        fetchOperateSystemBasic,
        fetchJvmBasic,
        diskUsageChart,
        heapMemoryGaugeChart,
        operateSystemRealtimeChart,
        jvmRealtimeChart,
    }
}